import { Context, Next } from "koa"
import { GameStage } from "../constant/GameStage"
import { SocketRoomEvent } from "../constant/SocketRoomEvent"
import Room, { IRoomVo } from "../data/Room"
import { IUserVo, User } from "../data/User"
import RoomManager from "../game/RoomManager"
import GameNotifier from "../websocket/GameNotifier"
import SocketManager from "../websocket/SocketManager"

export default class RoomController {
  // 加入房间
  static async joinRoom(ctx: Context, next: Next) {
    const { user }: { user: IUserVo } = ctx.request.body
    console.log('user:', user)

    // 加入房间
    let room: Room | null = null
    let index: number = -1
    try {
      const result = RoomManager.instance.intoRoom(new User(user))
      room = result.room
      index = result.index
      const player = result.room.getPlayerByUserId(user.id)

      if (player != undefined) {
        // socket emit
        GameNotifier.instance.sendJoinRoom(player, index, room.id)
      }
      // socket 掉线处理
      GameNotifier.instance.addDisconnectListener(user.id, () => {
        // 准备阶段
        // && room.referee.stage === GameStage.PREPARATION
        if (!room) { return }

        const playerIndex = room.findPlayerIndexById(user.id)
        if (playerIndex == -1) {
          return
        }

        // 离开房间
        const index = RoomManager.instance.leaveRoom(room.id, user.id)
        GameNotifier.instance.sendLeaveRoomByDisconnect(index, room.id)
      })
    } catch (error: any) {
      ctx.err({
        message: error.message
      })
      return
    }

    // 返回请求结果...
    ctx.succ({
      data: {
        // roomId: room?.id,
        room: room.getVo(),
        index
      }
    })
  }

  // 离开房间
  static async leaveRoom(ctx: Context, next: Next) {
    const { roomId, uid }: { roomId: string, uid: string } = ctx.request.body

    let index = -1
    try {
      // 离开房间
      index = RoomManager.instance.leaveRoom(roomId, uid)
      // socket emit
      GameNotifier.instance.sendLeaveRoom(uid, index, roomId)
    } catch (error: unknown) {
      ctx.err({
        message: (error as Error).message
      })
      return
    }

    // 返回请求结果...
    ctx.succ({
      data: {
        roomId,
        index
      }
    })
  }

}